#include "DeleteCommand.h"
#include "WherePart.h"
#include <iostream>
#include <boost\tokenizer.hpp>
using namespace boost;
using std::cout;

DeleteCommand::DeleteCommand(SQLSystem* sql): Command(sql)
{
}


DeleteCommand::~DeleteCommand()
{
}

//DELETE FROM TABLENAME WHERE ...
int DeleteCommand::execute(string str)
{
	Table* table;
	SQLSystem* system;
	system= getSystem();
	typedef tokenizer<char_separator<char> > token;
	char_separator<char> sep(" ","",drop_empty_tokens);
	token tok(str, sep);
	token::iterator tok_iter= tok.begin();
	++tok_iter;
	if(tok_iter == tok.end())	
		return false;
	if(helper->toUpperString(*tok_iter) != "FROM")
	{
		cout << "SYNTAX ERROR\n";
		return false;
	}
	++tok_iter;
	if(tok_iter == tok.end())	
		return false;
	table= system->getTableByName(*tok_iter);
	if(!table)
	{
		cout << "TABLE NOT FOUND\n";
		return false;
	}
	++tok_iter;
	if(tok_iter == tok.end())	
		return false;
	if(helper->toUpperString(*tok_iter) != "WHERE")
	{
		cout << "MISSING WHERE STATEMENT\n";
		return false;
	}
	++tok_iter;
	string s;
	vector<int> selectedRowsIndex;
	while(tok_iter!=tok.end())
	{
		if((*tok_iter)[0] == '\"')
		{
			string vString;	//this new string contains the real data without the double quote
			unsigned int i=1;
			while((*tok_iter)[i] !='\"')	//to add "tien phat" we need to merge the two token "tien and phat"
			{
				vString +=(*tok_iter)[i];
				++i;
				if(i >= (*tok_iter).size())
				{
					vString += " "; //add space between two words
					++tok_iter;	//next token to continue merging the string
					i=0;	//set i=0 so in the while condition we check again from the start
					continue;
				}
			}
			cout << vString <<endl;
			s +=vString;
		}
		else
			s +=*tok_iter;
		++tok_iter;
	}
	cout << s <<endl;
	WherePart whereClause;
	whereClause.selectRows(s, table);
	selectedRowsIndex= whereClause.getSelectedRowsIndex();
	for(unsigned i=0;i<selectedRowsIndex.size();i++)
	{
		table->removeRows(selectedRowsIndex[i]);
	}
}